package dao;

import utils.JDBCUtils;

import java.lang.reflect.*;
import java.sql.*;
import java.util.*;

/**
 * 抽象类，必须继承之后，才能实现
 * @author DuJiabao
 * @create 2021-01-16 10:55
 */
public abstract class BaseDAO<T> {
    private Class<T> clazz = null;  // 泛型类的Class实例

    {
        Type genericSuperclass = this.getClass().getGenericSuperclass(); // 获取当前类的带泛型的父类
        ParameterizedType parameterType = (ParameterizedType) genericSuperclass;
        Type[] actualTypeArguments = parameterType.getActualTypeArguments();  // 获取父类的泛型参数
        clazz = (Class<T>) actualTypeArguments[0];
    }

    /**
     * 查询操作，返回泛型对象数组
     *
     * @param sql
     * @param args
     * @return
     */
    public List<T> getForList(Connection conn, String sql, Object... args) { // 泛型方法
        PreparedStatement ps = null;
        ResultSet rs = null; // 保存查询结果
        ArrayList<T> ts = new ArrayList<>();  // 表对应的对象列表
        try {
            ps = conn.prepareStatement(sql);  // 语句传进statement中
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, i);
            }
            rs = ps.executeQuery(); // 获取查询结果
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            Field[] declaredFields = new Field[columnCount];
            for (int i = 0; i < columnCount; i++) {  //获取所有列名及属性
                String columnLabel = metaData.getColumnLabel(i + 1);
                Field declaredField = clazz.getDeclaredField(columnLabel);
                declaredField.setAccessible(true);
                declaredFields[i] = declaredField;
            }

            while (rs.next()) {
                T t = (T) clazz.newInstance();  // 实例化泛型对象
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);  // 获取数据库的值
                    if (columnValue != null) {
                        declaredFields[i].set(t, columnValue);  // 设置对象属性
                    }
                }
                ts.add(t);  // 添加进列表里
            }
            return ts;
        } catch (
                Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(ps);
            JDBCUtils.closeSource(rs);
        }
        return null;
    }

    /**
     * 获取单个对象
     *
     * @param conn
     * @param sql
     * @param args
     * @return
     */
    public T getInstance(Connection conn, String sql, Object... args) { // 泛型方法
        PreparedStatement ps = null;
        ResultSet rs = null; // 保存查询结果
        try {
            ps = conn.prepareStatement(sql);  // 语句传进statement中
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, i);
            }
            rs = ps.executeQuery(); // 获取查询结果
            ResultSetMetaData metaData = rs.getMetaData();  // 获取查询数据的元数据
            int columnCount = metaData.getColumnCount();  // 获取数据列数
            if (rs.next()) {
                T t = (T) clazz.newInstance();  // 实例化泛型对象
                for (int i = 0; i < columnCount; i++) { // 逐列数据导出
                    Object columnValue = rs.getObject(i + 1);  // 获取该列的值
                    String columnLabel = metaData.getColumnLabel(i + 1);  // 获取该列的列名
                    Field declaredField = clazz.getDeclaredField(columnLabel); // 获取对象属性的类
                    declaredField.setAccessible(true);  // 修改为accessible的

                    if (columnValue != null) {
                        declaredField.set(t, columnValue);  // 设置对象属性
                    }
                }
                return t; // 将t返回
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(ps);
            JDBCUtils.closeSource(rs);
        }
        return null;
    }

    public <E> E getValue(Connection conn, String sql, Object... args) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                return (E) rs.getObject(1);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeSource(ps);
            closeSource(rs);
        }
        return null;
    }

    /**
     * 增删改等SQL操作都可以在这进行
     *
     * @param conn
     * @param sql
     * @param args
     * @return 返回执行情况。either (1) the row count for SQL Data Manipulation Language (DML) statements
     * or (2) 0 for SQL statements that return nothing
     */
    public int update(Connection conn, String sql, Object... args) {
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            return ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeSource(ps);
        }
        return 0;
    }

    /**
     * 获取连接
     *
     * @return
     * @throws Exception
     */
    public Connection getConnection() throws Exception {
//      导入properties文件
        Properties config = new Properties();
        config.load(ClassLoader.getSystemClassLoader().getResourceAsStream("config.properties"));

        Class<?> driverClass = Class.forName(config.getProperty("Driver"));
//        底层已经做了，所以不需要自己注册了
//        Driver driver = (Driver) driverClass.newInstance();
//        DriverManager.registerDriver(driver);

        String url = config.getProperty("url");
        return DriverManager.getConnection(url, config);
    }

    /**
     * 关闭资源函数
     *
     * @param source
     */
    public static void closeSource(AutoCloseable source) {
        try {
            if (source != null) {
                source.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
